package com.flyme.module.auth.provider.service.impl;


import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.security.OpenUserAuth;
import com.flyme.common.core.utils.BeanConvertUtils;
import com.flyme.module.auth.provider.service.feign.SystemAccountClient;
import com.flyme.module.base.client.constants.BaseConstants;
import com.flyme.module.base.client.dto.SysAccountDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Security用户信息获取实现类
 *
 * @author liuyadu
 */
@Slf4j
@Service("userDetailService")
public class UserLoginServiceImpl implements UserDetailsService {

    @Autowired
    private SystemAccountClient systemAccountClient;
    /**
     * 认证中心名称
     */
    @Value("${spring.application.name}")
    private String AUTH_SERVICE_ID;

    @Override
    public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException {
        ResultBody<SysAccountDto> resp = systemAccountClient.login(username);
        SysAccountDto account = resp.getData();
        if (account == null) {
            throw new UsernameNotFoundException("系统用户 " + username + " 不存在!");
        }
        String accountType = account.getAccountType();
        Integer status = account.getStatus();
        boolean accountNonLocked = !status.equals(BaseConstants.USER_STATE_LOCKED);
        boolean credentialsNonExpired = true;
        boolean enable = BaseConstants.USER_STATE_NORMAL.equals(status) ? true : false;
        boolean accountNonExpired = true;
        Map userProfile = BeanConvertUtils.objectToMap(account.getUserProfile());
        return new OpenUserAuth(AUTH_SERVICE_ID, account.getUserId(), account.getUserProfile().getCompanyId(), account.getAccount(), account.getPassword(), account.getUserProfile().getAuthorities(), accountNonLocked, accountNonExpired, enable, credentialsNonExpired, userProfile, accountType, account.getAvatar(), account.getNickName());
    }
}
